<?php 

include("../accesscheck.php"); 
kan_import('FeedbackManager');

$feedback = new FeedbackManager();
$db = $feedback->getDatabase();

if( isset($_POST['action']) && $_POST['action'] == "add_category" ) {

    $insertSQL = sprintf("INSERT INTO feedback_categories (SiteID, CategoryName, CategoryTag, CategoryDesc, FwdToEmail, FwdEmail, DateCreated) VALUES (%s, %s, %s, %s, %s, %s, now() ) ",
        $db->sanitizeInput($siteid, "int"),
        $db->sanitizeInput(kan_get_parameter('CategoryName'),"text"),
        $db->sanitizeInput(kan_get_parameter('CategoryTag'),"text"),
        $db->sanitizeInput(kan_get_parameter('CategoryDesc'),"text"),
        $db->sanitizeInput(kan_get_parameter('FwdToEmail', 'false'), "text"),
        $db->sanitizeInput(kan_get_parameter('FwdEmail'), "text")
    );

    $insert_id = $db->query($insertSQL)->getInsertId();

    echo json_encode(
        array(
            "category_id" => $insert_id,
            "category_name" => kan_get_parameter('CategoryName'),
            "category_desc" => kan_get_parameter('CategoryDesc')
        )
    );

} else if( isset($_POST['action']) && $_POST['action'] == "load_category" ) {

    $category_id = $_POST['category_id'];
    $query = "SELECT * FROM feedback_categories WHERE id = $category_id";
    $result_array = $db->query($query)->getRow();

    echo json_encode($result_array);


} else if( isset($_POST['action']) && $_POST['action'] == "update_category" ) {

    $updateSQL = sprintf("UPDATE feedback_categories SET SiteID = %s, CategoryName = %s, CategoryTag = %s, CategoryDesc = %s, FwdToEmail = %s, FwdEmail = %s WHERE id = %s ",
        $db->sanitizeInput($siteid, "int"),
        $db->sanitizeInput(kan_get_parameter('CategoryName'),"text"),
        $db->sanitizeInput(kan_get_parameter('CategoryTag'),"text"),
        $db->sanitizeInput(kan_get_parameter('CategoryDesc'),"text"),
        $db->sanitizeInput(kan_get_parameter('FwdToEmail', 'false'), "text"),
        $db->sanitizeInput(kan_get_parameter('FwdEmail'), "text"),
        $db->sanitizeInput(kan_get_parameter('category_id'),"int")
    );

    $db->query($updateSQL,true);

    echo json_encode(
        array(
            "category_id" => kan_get_parameter('category_id'),
            "category_name" => kan_get_parameter('CategoryName'),
            "category_desc" => kan_get_parameter('CategoryDesc')
        )
    );

} else if( isset($_POST['action']) && $_POST['action'] == "delete_category" ) {
    $category_id = $_POST['category_id'];
    $query = "DELETE FROM feedback_categories WHERE id = $category_id ";
    $db->query($query, true);

} else if( isset($_POST['action']) && $_POST['action'] == "load_messages" ) {

    $cat = isset($_POST['cat']) ? $_POST['cat'] : -1;

    $query = "SELECT fb.* FROM feedback fb "
        . "INNER JOIN feedback_categories fbc ON fb.CategoryID = fbc.id "
        . "WHERE fbc.SiteID = $siteid AND fb.CategoryID = $cat "
        . "ORDER BY fb.date_posted DESC, fb.id DESC ";

    $rsMessages = mysqli_query($config, $query) or die(mysqli_error());

    echo "<table id='msg_list_table' width='100%' border='0' cellpadding='1' cellspacing='0'>";

    $icount = 0;
    $count = 1;

    if( mysqli_num_rows($rsMessages) > 0 ) {
        while( $row_rsMessages = mysqli_fetch_assoc($rsMessages) ) {
            $status = $row_rsMessages['status'];
            $id = $row_rsMessages['id'];
            $name = $row_rsMessages['name'];
            $subject = $row_rsMessages['subject'];
            $date = $row_rsMessages['date_posted'];
            ++$icount; // increase the item count

            echo "<tr id='msg-row-$id' class='msg$status'>
					 <td width='40' align='center' valign='top'>
						<input type='checkbox' name='msg$icount' id='msg$icount' value='$id' />
					 </td>
					 <td width='180' align='left' valign='top'>$name</td>
					 <td width='200' align='left' valign='top'>
						<a class='message-link' id='$id' href='#'>$subject</a>
					 </td>
					 <td align='left' valign='top'>$date</td>
				  </tr>";
        }
    } else {
        echo "<tr>
				<td colspan=4 align=left valign=top style='padding: 3px;'>No Feedback Posted</td>
			  </tr>";
    }

    echo "</table>";
    echo "<input type='hidden' id='items' name='items' value='$count'  />";


} else if( isset($_POST['action']) && $_POST['action'] == "move_messages" ) {

    $category_id = $_POST['category_id'];
    $msg_ids = $_POST['msg_ids'];
    $query = "UPDATE feedback SET CategoryID = $category_id WHERE id IN ($msg_ids)";
    $result = mysqli_query($config, $query) or die(mysqli_error());

    echo '<div class="msg_processed">' . count( explode(",", $msg_ids)) . ' Messages Moved</div>';

} else {


    if( !isset($_POST['action']) ) {
        $colname_detfeedback = "-1";
        if (isset($_GET['id'])) {
            $colname_detfeedback = $_GET['id'];
            $id = $_GET['id'];

            $mark = "read";
            if( isset($_GET['mark']) ) {
                $mark = $_GET['mark'];
            }

            $updateSQL = "UPDATE feedback SET status = '$mark' WHERE id = $id";
            $detfeedback = mysqli_query($config, $updateSQL) or die(mysqli_error());

            /*if( $mark == "unread" ) {
			header("Location: feedback.php?rstat=read");
			exit;
		  }*/
        }

        $query_detfeedback = sprintf("SELECT * FROM feedback WHERE id = %s", $db->sanitizeInput($colname_detfeedback, "int"));
        $detfeedback = mysqli_query($config, $query_detfeedback) or die(mysqli_error());
        $row_detfeedback = mysqli_fetch_assoc($detfeedback);
        $totalRows_detfeedback = mysqli_num_rows($detfeedback);

        ?>
        <div class="pane-header" style="font-weight: normal; line-height: 24px;">
            <div>
                <div style="font-size: 18px;">
                            <?php echo $row_detfeedback['subject']; ?>
                </div>

                <div>
                    <span style="margin-right: 20px;"><strong>Sender:</strong> <?php echo $row_detfeedback['name']; ?></span>
                    <span style="margin-right: 20px;"><strong>Email:</strong> <a href="mailto:<?php echo $row_detfeedback['email']; ?>"><?php echo $row_detfeedback['email']; ?></a></span>
                    <span style="margin-right: 20px;"><strong>Tel: </strong><?php echo $row_detfeedback['phone_number']; ?></span>
                </div>
            </div>
        </div>

        <div class="pane-content">
             <?php echo str_replace("\n", "<br />" ,$row_detfeedback['message']); ?>
        </div>

        <?php
        mysqli_free_result($detfeedback);

    } else {
        $action = $_POST['action'];
        $msgs = urldecode($_POST['msgs']);
        $msgs = explode("|",$msgs);

        for($i = 0; $i < count($msgs); $i++ ) {
            $sql = "";
            $id = $msgs[$i];

            if( $action == "mark_unread" ) {
                $mark = "unread";
                $sql = "UPDATE feedback SET status = '$mark' WHERE id = $id";
            } else if( $action == "mark_read" ) {
                $mark = "read";
                $sql = "UPDATE feedback SET status = '$mark' WHERE id = $id";
            } else if( $action == "delete" ) {
                $sql = "DELETE FROM feedback WHERE id = $id";
            }

            //echo $sql . "<br />";
            $result = mysqli_query($config, $sql) or die(mysqli_error());
        }

        echo '<div class="msg_processed">' . count($msgs) . ' Messages Processed</div>';
    }

}
?>